<?php

declare (strict_types = 1);

namespace app\admin\controller;

use app\admincommon\controller\AdminController;
use think\facade\Db;

class UploadToInsert extends AdminController{

    //上传图片并保存到数据库

    public function index(){
        
        $file = $_FILES['file'];

        $id=input("id");

        $filename = basename($file['name']);

        $file_ext = strtolower(substr($filename, strrpos($filename, '.') + 1));

        $imagename = $this->GetDateStr()."_".$this->GetRandStr(6).".".$file_ext;

        $path="./upload/".$imagename;

        
        if(is_uploaded_file($file['tmp_name'])){
            
            if(move_uploaded_file($file['tmp_name'],$path)){

                $url="/upload/".$imagename;

                $item["parentid"]=$id;
                $item["src"]=$url;

                // {
                //     "errno": 0, // 注意：值是数字，不能是字符串
                //     "data": {
                //         "url": "xxx", // 图片 src ，必须
                //         "alt": "yyy", // 图片描述文字，非必须
                //         "href": "zzz" // 图片的链接，非必须
                //     }
                // }

                $imageid = Db::table("ea_system_image")->insertGetId($item);

                return json(["errno"=>0,"data"=>["url"=>$url,"href"=>$url,"imageid"=>$imageid,"id"=>$id]]);
            }

        }else{

            // {
            //     "errno": 1, // 只要不等于 0 就行
            //     "message": "失败信息"
            // }

            return json(["errno"=>1,"message"=>"上传失败"]);

        }


    }

    function GetRandStr($length){
        //字符组合
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len = strlen($str)-1;
        $randstr = '';
        for ($i=0;$i<$length;$i++) {
            $num=mt_rand(0,$len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }

    function GetDateStr(){
        return date( "Ymd-h-i-s");
    }


    //编辑器上传图片 end




}